<?php
namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\model\AuthRole;
use app\common\model\AuthRule;
use think\Controller;
use think\Db;
use think\Request;

class Auth extends Common
{

	public function rule()
	{
		if(Request::instance()->isAjax()){

    		$data = input('get.');

    		$users = AuthRule::order('rule_id desc')->paginate($data['limit']);

    		exit(json_encode(['code'=>0,'count'=>$users->total(),'data'=>$users->items()]));

    	}else{
    		return $this->fetch();
    	}
	}

	public function rule_add()
	{
		$data = input('post.');

		$res = AuthRule::create($data);

		if($res){
			$this->success('成功');
		}else{
			$this->error('失败');
		}
	}

	public function role()
	{
		if(Request::instance()->isAjax()){

    		$data = input('get.');

    		$users = AuthRole::order('role_id desc')->paginate($data['limit']);

    		exit(json_encode(['code'=>0,'count'=>$users->total(),'data'=>$users->items()]));

    	}else{
    		return $this->fetch();
    	}
	}

	public function role_add()
	{
		if(Request::instance()->isAjax()){

			$data = input('post.');

			$data['rules'] = implode(',',$data['rule_id']);

			$res = AuthRole::create($data);

			if($res){
				$this->success('成功');
			}else{
				$this->error('失败');
			}

		}else{

			$rules = Db::name('auth_rule')->select();

			$temp =[];

			foreach ($rules as $rule) {
				$temp[$rule['cate_name']][] = $rule;
			}

			$this->assign('rules',$temp);

			return $this->fetch();
		}
	}

	public function change_role_status()
	{
		// $this->error("提交失败");
    	$role_id = input('role_id');

    	$role = AuthRole::get($role_id);

    	if($role->status==1){
    		$role->status = 0;
    	}else{
    		$role->status = 1;
    	}

    	$res = $role->save();

    	if($res){
    		$this->success("提交成功");
    	}else{
    		$this->error("提交失败");
    	}
	}

	public function admin()
	{
		return $this->fetch();
	}
}
